import {Component} from '@angular/core';
import {
  ActionSheetController,
  IonicPage,
  ModalController,
  NavController,
  NavParams, PopoverController,
  ViewController
} from 'ionic-angular';
import {NativeProvider} from "@providers/natives/native";
import {WorkerProvider} from "@providers/interface/worker";
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {Util} from "@providers/util";
import {ImagePickerObject} from "@common/ImagePickerObject";
import {ImageManipulationProvider} from "@providers/interface/image-manipulation";
import {AiProvider} from "@providers/natives/ai";

/**
 * Generated class for the WorkerLookFinishDriverPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-worker-look-finish-driver',
  templateUrl: 'worker-look-finish-driver.html',
})
export class WorkerLookFinishDriverPage {

  picList: any[] = []; //手机选择的图片
  remarks: string;//备注
  foolernum: number;//楼层
  param = this.navParams.data;
  userInfo: any;
  isLift: boolean = false;
  isApp;
  codeList: any[] = [];
  //返仓失败
  isFailureOfDistribution: boolean = false;
  PSSBYYKEY: any;
  PSSBYY: any;//配送失败原因
  SP;

  addCode = false;

  data: any = {CQTP: ''};
  CQTP: any;//签名图片base64格式};//完工提交的数据

  run: any[] = [];//next方法是否调用
  num: number;//计数器
  cacheOrder: any;//缓存的已完工订单
  SPLB: any = this.navParams.data.CSM_SORDERITEM;
  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private viewCtrl: ViewController,
              private actionSheetCtrl: ActionSheetController,
              private native: NativeProvider,
              private dialog: DialogProvider,
              private storageService: StorageProvider,
              private worker: WorkerProvider,
              private modalCtrl: ModalController,
              private imageMpn: ImageManipulationProvider,
              private popoverCtrl: PopoverController,
              private ai: AiProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WorkerLookFinishDriverPage');
    this.init();
  }

  /**
   * 初始化数据
   */
  init() {
    this.isApp = this.native.isCordova;
    this.userInfo = this.storageService.read("userInfo");
    this.remarks = this.param.BZ;
    this.isLift = this.param.SFDT == 1;
    this.foolernum = this.param.FLOOR;
    this.getSPMC();
    this.imagedowablelode();
    this.initCacheOrder();
    this.worker.getNJMSFBT().then(message => {
      let data = JSON.parse(JSON.stringify(message))['data'];
      if (!Util.isNull(data)) {
        this.addCode = data[0].ID === '1';
      } else {
        this.addCode = false;
      }
    }).then(() => {
      this.nnext(0);
    }).catch(error => {
      this.nnext(0);
      console.log(error);
    });
  }

  submit() {
    //完工
    let _commit = (yzm?) => {
      if (yzm) {
        this.data["YZM"] = yzm;
      }
      // 提交数据
      if (!this.foolernum) {
        this.dialog.showAlert("请填写楼层！");
        this.dialog.hideLoading();
        return;
      }
      if (isNaN(this.foolernum)) {
        this.dialog.showAlert("楼层必须为阿拉伯数字！");
        this.dialog.hideLoading();
        return;
      }

      let lift = 0;
      if (this.isLift) {
        lift = 1;
      }
      // let data: any = {};
      this.data["shcodeList"] = [];//内外机编码列表
      for (let i = 0; i < this.codeList.length; i++) {
        let spcode: any[] = this.codeList[i]["codes"];
        if ((!spcode[1].code) && this.addCode) {
          this.dialog.showAlert("请填写内机编码");
          this.dialog.hideLoading();
          return;
        }
        for (let j = 0; j < spcode.length; j++) {
          let code: any = {};
          code["code"] = spcode[j].code;
          code["lx"] = spcode[j].lx;
          this.data["shcodeList"].push(code);
          console.log("hello :" + JSON.stringify(code));
        }
      }

      this.data['codeList'] = this.codeList;
      this.data["signer"] = this.userInfo.PARTYID;
      this.data["floor"] = this.foolernum;//楼层
      this.data["bz"] = this.remarks;
      let pic: any[] = [];
      for (let i = 0; i < this.picList.length; i++) {
        pic.push(this.picList[i]["url"])
      }
      this.data["picture"] = pic.join(',');//照片
      this.data["id"] = this.param.ID;//订单号
      this.data["lift"] = lift;//是否电梯
      this.data["worklist"] = this.param.work;//搬运工人列表
      this.data["lines"] = this.param.CSM_SORDERITEM;//商品列表
      if (this.isFailureOfDistribution) {
        this.data["PSSBYY"] = this.PSSBYY;
        this.data["PSBJ"] = 1;
      } else {
        this.data["PSBJ"] = 0;
      }
      this.dialog.showLoading();
      console.log("完工参数:" + JSON.stringify(this.data));
      this.worker.wandan(this.data).then((message) => {
        this.dialog.hideLoading();
        this.dialog.showAlert("完工成功！");
        let bor: boolean = true;
        this.viewCtrl.dismiss(bor);
      }, error => {
        this.dialog.hideLoading();
        this.dialog.showAlert("完工失败:" + error);
      });
    };

    //验证
    let _next = () => {
      if (this.param.DJLX == 10) {
        if (this.userInfo.YZMCS == 1) {
          this.dialog.showRadioOrCheckbox((data) => {
              if (!Util.isNull(data.yzm)) {
                _commit(data.yzm);
              } else {
                this.dialog.showAlert("请输入验证码！");
                this.dialog.hideLoading();
                return;
              }
            }, "是否完成！",
            [{
              name: 'yzm',
              type: 'text',
              placeholder: '请输入验证码'
            }])
        } else {
          this.dialog.showConfirm(() => {
            console.log("1完工参数:" + JSON.stringify(this.data));
            _commit()
          }, "是否完成！")
        }
      } else {
        this.dialog.showConfirm(() => {
          console.log("2完工参数:" + JSON.stringify(this.data));
          _commit()
        }, "是否完成！")
      }
    };

    //收费
    let _sf = () => {
      if (this.userInfo.GSCS == '5') {
        //查询客户收费金额大于0
        this.cacheOrder["orderID"] = this.param.ID;
        this.cacheOrder["serviceTypeId"] = this.param.SERVICETYPEID;

        this.worker.getSHFY({"DH": this.param.ID, "KHSF": "1", "STATUSID": "NORETURNED"}).then(v => {
          console.log("khfy:" + JSON.stringify(v));
          if (v[0].PRICE == null) {
            _next();
            return;
          }
          this.cacheOrder["sum"] = v[0].PRICE;
          //是否是分销
          this.worker.getDjlx({"ID": this.param.ID}).then(v => {
            if (this.cacheOrder["sum"] != null && v.DJLX == "8") {
              let popover = this.popoverCtrl.create('RpayPage', this.cacheOrder, {cssClass: 'jl_mask'});
              popover.onDidDismiss((data) => {
                if (data) {
                  this.navCtrl.pop();
                }
                _next();
              });
              popover.present();
            } else {
              _next();
              return;
            }
          });
        });
      }
    };

    let modal = this.modalCtrl.create("SignaturePadPage");
    modal.onDidDismiss(_data => {
      if (Util.isNull(_data)) return;
      this.data["CQTP"] = _data['imageData'];
      console.log("cqtp:" + this.data.CQTP);
      _sf();
    });

    modal.present();

  }

  //回车增加编号栏事件
  shuRus(event, SP: any, i: any) {
    if (event.keyCode == 13) {
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {
            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {
          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }

  }

  //失去焦点增加编号栏事件
  sJs(v, SP: any, i: any) {
    if (!Util.isNull(v.code)) {
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {
            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {
          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }
  }

  /***
   * 增加一对机器编码
   * @param item
   * @param ary
   */
  nnext(item: any) {
    //循环判断编号框是否大于商品数量
    let cd: any = 0;
    let cds: any = 0;
    let spnum: number = 0;
    for (let i = 0; i < this.SPLB.length; i++) {
      cd += this.SPLB[i]['NUM'];
    }
    for (let j = 0; j < this.codeList.length; j++) {
      if (this.codeList[j]['codes']['0']['lx'] == '1') {
        cds++;
        if (cds == cd) {
          return
        }
      }
    }
    console.log(JSON.stringify(this.codeList));
    let code = this.codeList.filter(value => {
      return value.lx == '1' && value.code.trim() == '';
    });
    if (code.length > 0) {
      return;
    }

    for (let k = 0; k <= item; k++) {
      spnum = spnum + this.SPLB[k]['NUM'];
    }
    if (cds == 0) {
      this.num = 0;
    } else if (cds == spnum) {
      this.num = 0;
      item++;
    }
    let ary: any[];
    ary = this.initCode(this.SPLB[item]['codelist']);

    let a: any = Object.assign(JSON.parse(JSON.stringify(this.SPLB[item])), {codes: ary});
    if (item == 0 && this.codeList.length == 0) {
      this.codeList = [a];
    } else {
      this.codeList.push(a);
    }

  }

  /**
   * 初始化codes值
   */
  initCode(code) {
    let ary: any[] = [];
    let length: number;
    if (this.addCode) {
      length = 3;
    } else {
      length = 2;
    }
    for (let k = 0; k < length; k++) {
      if (ary.length == 0) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 1) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "1"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "1"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "1"
          });
        }
      } else if (ary.length == 1) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 2) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "2"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "2"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "2"
          });
        }
      } else if (ary.length == 2) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 3) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "3"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "3"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "3"
          });
        }
      }
    }
    return JSON.parse(JSON.stringify(ary));
  }

  /**
   * 扫一扫获取外机编码
   * @param vcode 编码
   * @param SP
   * @param i
   */
  scanWJBM(vcode: any, SP: any, i: any) {
    this.native.openScanner().then(v => {
      vcode.code = v;
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {
            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {
          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }).catch(e => console.log(e));
  }

  /**
   * 扫一扫获取内机编码
   * @param vcode 编码
   * @param SP
   * @param i
   */
  scanNJBM(vcode: any, SP: any, i: any) {
    this.native.openScanner().then(v => {
      vcode.code = v;
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {
            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {
          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }).catch(e => console.log(e));
  }

  FanCang() {
    if (this.isFailureOfDistribution) {
      this.getPSSBYY((value) => {
        this.PSSBYYKEY = value.ID;
        this.PSSBYY = value.PSSBYY;
      });
    }
  }

  getPSSBYY(okFun: (Address: any) => void, LEVELS ?) {
    let json = {"PSSB": 1} /*{"TYPE": "css_azfh"}*/;
    if (!LEVELS) LEVELS = 1;
    this.worker.getPSSBYY(json).then(MESSAGE => {
      let temp = [];

      let obj: any[] = MESSAGE.data;
      if (LEVELS < obj[0].LEVELS) return;
      let titleText = "请选择失败原因";
      if (obj[0].LEVELS == 1) {
        titleText = "请选择原因";
      }
      for (let i = 0; i < obj.length; i++) {
        let item: any = obj[i];
        temp.push({
          text: obj[i].PSSBYY,
          handler: (fan) => {
            okFun(item);
          }
        });
        temp.push()
      }
      let actionSheet = this.actionSheetCtrl.create({
        title: titleText,
        buttons: temp
      });
      actionSheet.present();

    })
  }

  getSPMC() {
    this.SP = this.param.CSM_SORDERITEM;
  }

  imagedowablelode() {
    this.imageMpn.imagedowablelode({ID: this.param.ID}).then(data => {
      let datas: any[] = data['data'];
      let files: ImagePickerObject[] = [];
      for (let i = 0; i < datas.length; i++) {
        let file = new ImagePickerObject();
        file.url = datas[i]['PICTURE'];
        file.id = datas[i]['XLH'];
        files.push(file);
      }
      this.picList = files
    }).catch(() => {
    });
  }

  delImage(event) {
    this.imageMpn.delImage({XLH: event[0].id}).then(() => {
      //this.imagedowablelode();
    }).catch(() => {
    });
  }

  imageUpload(event) {
    for (let i = 0; i < event.length; i++) {
      this.imageMpn.imageUpload({
        ID: this.param.ID,
        PICTURE: event[i].url
      }).then((data) => {
        event[i].id = data.message;
      }).catch((error) => {
      });
    }
  }

  push(page: string) {
    this.navCtrl.push(page);
  }

  dismiss(work?: any) {
    if (work) {
      this.viewCtrl.dismiss(work);
      return;
    }
    this.viewCtrl.dismiss();
  }

  /**
   * 初始化缓存的已完工订单
   */
  initCacheOrder() {
    /*this.cacheOrder = this.storageService.read("cacheOrder");
     if (Util.isNull(this.cacheOrder)){*/
    this.cacheOrder = {
      "id": this.param.ID,//单号
      "signer": this.userInfo.PARTYID,
    }
    // }
  }

}
